package com.hmyd.hmyd_android.ui;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.net.Uri;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hmyd.hmyd_android.AppBasic;
import com.hmyd.hmyd_android.R;
import com.hmyd.hmyd_android.commons.Constants;
import com.hmyd.hmyd_android.commons.UrlConstant;
import com.hmyd.hmyd_android.crypto.Crypto;
import com.hmyd.hmyd_android.dto.User;
import com.hmyd.hmyd_android.utils.MyToast;
import com.hmyd.hmyd_android.utils.PreferencesUtils;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.shangzhu.apptrack.AppTrack_2423;

/**
 * 登录
 * 
 * @author wangc
 * 
 */
@ContentView(R.layout.activity_login)
public class LoginActivity extends BasicActivity {

	private final int SEND_REGISTER_VERIFY_CODE = 0;
	private final int REGISTER = 1;
	private final int LOGIN = 2;

	private String phoneNum;
	private String passwd;

	// 标题栏
	@ViewInject(R.id.home_title)
	public View home_title;
	@ViewInject(R.id.home_title_txt)
	public TextView home_title_txt;
	@ViewInject(R.id.home_right)
	public TextView home_right;

	@ViewInject(R.id.ed_phone)
	private EditText mEdPhone;
	@ViewInject(R.id.ed_passwd)
	private EditText mEdPasswd;
	@ViewInject(R.id.btn_login)
	private Button mBtnLogin;

	@OnClick({ R.id.tv_forget_passwd, R.id.btn_login, R.id.tv_not_member, R.id.btn_more_contact })
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.tv_forget_passwd:// 忘记密码
			forgetPasswd();
			break;
		case R.id.btn_login:// 登录
			login();
			break;
		case R.id.tv_not_member:// 不是会员，注册
			startActivity(new Intent(getApplicationContext(), RegisterActivity.class));
			finish();
			break;
		case R.id.btn_more_contact:// 联系电话
			Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:400-969-1688"));
			startActivity(intent);
			break;
		default:
			break;
		}
	}

	private void login() {

		if (TextUtils.isEmpty(phoneNum)) {
			MyToast.showHMToast(LoginActivity.this, false, "请输入手机号码");
			return;
		}
		if (TextUtils.isEmpty(passwd)) {
			MyToast.showHMToast(LoginActivity.this, false, "请输入账户密码");
			return;
		}

		RequestParams params = new RequestParams();
		params.addBodyParameter("username", phoneNum);
		params.addBodyParameter("password", passwd);

		onRequest(LOGIN, UrlConstant.LOGIN, HttpMethod.POST, params);

	}

	private void forgetPasswd() {
		startActivity(new Intent(getApplicationContext(), FindPasswordActivity.class));
	}

	@Override
	public void onPostSuccess(int postId, String result) {
		Gson gson = new Gson();
		java.lang.reflect.Type type2 = new TypeToken<User>() {
		}.getType();
		User user = gson.fromJson(result, type2);

		PreferencesUtils.putString(this, PreferencesUtils.USER_PHONE, phoneNum);
		PreferencesUtils.putString(this, PreferencesUtils.USER_PASSWORD,
				Crypto.encryptAES(passwd, Crypto.PRIVATEKEY));

		AppBasic.isLogin = true;
		AppBasic.isCheckIned = user.isCheckIned;
		AppBasic.totalScore = user.score;
		AppBasic.certNo = user.certNo;
		AppBasic.realName = user.realName;
		AppBasic.avatar = user.avatar;
		AppBasic.username = user.username;
		AppBasic.nickname = user.nickname;
		AppBasic.urlToken = user.urlToken;
		AppBasic.securityLevel = user.securityLevel;
		AppBasic.isSetSecurityCode = user.isSetSecurityCode;
		AppBasic.tel = user.tel;
		AppBasic.email = user.email;
		AppBasic.isVerifiedEmail = user.isVerifiedEmail;
		AppBasic.isSetSecurityQuestion = user.isSetSecurityQuestion;
		AppBasic.unReadMessageCount = user.unReadMessageCount;
		AppBasic.bindQQ = user.bindQQ;
		AppBasic.isBind = user.isBind;
		AppBasic.rewardScore = user.rewardScore;
		AppBasic.nextTimeScore = user.nextTimeScore;
		AppBasic.isCanUpdateNickname = user.isCanUpdateNickname;

		MyToast.showToast(this, "登录成功");
		// 加入99统计
		AppTrack_2423.countView(Constants.LoginPageTopic, "登录页面", "");

		Intent intent = new Intent();
		intent.putExtra("loginSuccess", true);
		setResult(RESULT_OK, intent);

		AppBasic.getInstance().finishActivity(this);

	}

	@Override
	public void onPostFailure(int postId, String msg) {
		// 跳转到设备验证界面
		try {
			JSONObject jsonObject = new JSONObject(msg);
			JSONObject jsonObject2 = new JSONObject(jsonObject.getString("error"));
			long code = jsonObject2.getLong("code");
			if (code == 100082) {
				Intent intent = new Intent();
				intent.setClass(this, ChangeDeviceLoginActivity.class);
				intent.putExtra("phone", phoneNum);
				intent.putExtra("passwd", passwd);
				startActivityForResult(intent, 101);
				AppBasic.getInstance().finishCurrentActivity();
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}

	}

	@Override
	protected void setParams() {
		mEdPasswd.addTextChangedListener(loginWatcher);
		mEdPhone.addTextChangedListener(loginWatcher);
		home_title.setOnTouchListener(touch);
		home_title_txt.setText("登录");
	}

	@Override
	protected void leftButton() {
		AppBasic.getInstance().finishCurrentActivity();
	}

	@Override
	protected void rightButton() {

	}

	private TextWatcher loginWatcher = new TextWatcher() {

		@Override
		public void afterTextChanged(Editable s) {
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count, int after) {
		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {
			loginPatterns();
		}
	};

	protected void loginPatterns() {
		phoneNum = mEdPhone.getText().toString().trim();
		passwd = mEdPasswd.getText().toString().trim();

		// if (!TextUtils.isEmpty(phoneNum) && !TextUtils.isEmpty(passwd)) {
		// mBtnLogin.setEnabled(true);
		// } else {
		// mBtnLogin.setEnabled(false);
		// }
	}

	@Override
	protected void onActivityResult(int arg0, int arg1, Intent arg2) {
		super.onActivityResult(arg0, arg1, arg2);
		if (arg0 == 101 && arg1 == RESULT_OK) {
			AppBasic.getInstance().finishCurrentActivity();
		}
	}

	@Override
	protected void onDestroy() {
		AppBasic.getInstance().finishActivity(this);
		super.onDestroy();
	}
	
}
